﻿using System.ComponentModel;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System;
using nRoute.Components;
using SilverlightSudokuPuzzle;

namespace nRoute.Samples.Sudoku.Model
{
    [DataContract]
    public class Game : INotifyPropertyChanged
    {
        private TimeSpan _playTime = TimeSpan.Zero;

        #region Properties

        [DataMember]
        public GameLevel Level { get; set; }

        [DataMember]
        public List<Box> Board { get; set; }

#endregion

#region Methods

        public void NewGame()
        {
            // get the puzzle values 
            var _board = new List<Box>();
            var _puzzleValues = (new SudokuPuzzle()).GetPuzzle((int)Level).Split('|');

            // set up the cells
            for (int i = 0; i < 9; i++)
            {
                for (int j = 0; j < 9; j++)
                {
                    _board.Add(new Box() 
                    { 
                        Col = i,
                        Row = j,
                        IsPreDefined = _puzzleValues[0][i * 9 + j] == '0',
                        SuggestedValue = BoxValue.None,
                        ExpectedValue = ParseValue(_puzzleValues[1][i * 9 + j]),
                    });
                }
            }

            // and set that as the board
            Board = _board;
        }

        public void ResetBoard()
        {
            foreach (var _box in Board)
            {
                if (!_box.IsPreDefined) _box.SuggestedValue = BoxValue.None;
            }
        }

        public void HintMove()
        {
            foreach (var _box in Board)
            {
                if (!_box.IsPreDefined && _box.SuggestedValue == BoxValue.None)
                {
                    _box.SuggestedValue = _box.ExpectedValue;
                    break;
                }
            }
        }

        public void SolveGame()
        {
            foreach (var _box in Board)
            {
                if (!_box.IsPreDefined) _box.SuggestedValue = _box.ExpectedValue;
            }
        }

        public bool VerifyGame()
        {
            foreach (var _box in Board)
            {
                if (!_box.IsPreDefined && _box.SuggestedValue != _box.ExpectedValue)
                {
                    return false;
                }
            }
            return true;
        }

#endregion

#region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

#endregion

#region Helpers

        static BoxValue ParseValue(object value)
        {
            return (BoxValue) Enum.Parse(typeof (BoxValue), Convert.ToString(value), true);
        }

#endregion

    }
}
